package com.core.ui.controls;

import com.core.utils.KeyValueDictionary;
import com.model.KeyValue;

public class ControlSelect
        extends UIControl {

	private String             caption;
	private String             formFieldName;
	private KeyValue           data;
	private KeyValueDictionary values;
	private boolean            readonly = false;



	public KeyValueDictionary getValues () {

		return values;
	}



	public void setValues ( KeyValueDictionary values ) {

		this.values = values;
	}



	public boolean isReadonly () {

		return readonly;
	}



	public void setReadonly ( boolean readonly ) {

		this.readonly = readonly;
	}



	public String getCaption () {

		return caption;
	}



	public void setCaption ( String caption ) {

		this.caption = caption;
	}



	public String getFormFieldName () {

		return formFieldName;
	}



	public void setFormFieldName ( String formFieldName ) {

		this.formFieldName = formFieldName;
	}



	public KeyValue getData () {

		return data;
	}



	public void setData ( KeyValue data ) {

		this.data = data;
	}



	@Override
	public String toString () {

		String result = null;

		KeyValue data = null;
		if ( this.data == null ) {
			data = new KeyValue("", "");
		} else {
			data = this.data;
		}

		if ( readonly ) {
			result = String.format("<strong class=\"name\">%s</strong>%s", this.caption, data.getValue());
			return result;

		}

		StringBuilder sb = new StringBuilder();
		if ( values != null ) {

			for ( String valueKey : values.keySet() ) {
				boolean isSelected = false;

				String key = (valueKey == null) ? "" : valueKey;
				isSelected = key.equalsIgnoreCase(data.getKey());

				String foundValue = (String) values.get(key);
				String value = (foundValue == null) ? "-------" : foundValue;

				String strSelected = String.format("%s", isSelected ? "selected=\"selected\"" : "");
				sb.append(String.format("<option value=\"%s\" %s>%s</option>", key, strSelected, value));
			}

		} else {
			sb.append(String.format("<option value=\"%s\">%s</option>", data.getKey(), data.getValue()));
		}


		result = String.format(
		        "<strong class=\"name\">%s</strong><select name=\"%s\" class=\"long-input\">%s</select>",
		        this.caption,
		        this.formFieldName,
		        sb.toString());

		return result;
	}
}
